import requests
import json
import csv

# 修正URL和转义字符
url = 'https://slamdunk.sports.sina.com.cn/api'

headers = {
    'Accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01',
    'Accept-Encoding': 'gzip, deflate, br, zstd',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'Priority': 'u=1, i',
    'Referer': 'https://slamdunk.sports.sina.com.cn/rank',
    'Sec-Ch-Ua': '"Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99"',
    'Sec - Ch - Ua - Mobile': '?0',
    'Sec-Ch-Ua-Platform': '"Windows"',
    'Sec-Fetch-Dest': 'empty',
    'Sec - Fetch - Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0'
}

params = {
    'p': 'radar',
    's': 'team_standing',
    'a': 'conference',
    # '_': 1715062589025  # 这个时间戳参数可能是动态的，确保它是最新的
}

response = requests.get(url, headers=headers, params=params)
comments = []
# 检查响应状态码
if response.status_code == 200:
    # 直接解析JSON数据，假设返回的是纯JSON格式
    try:
        data_json = response.json()  # 使用requests的内置方法解析JSON
        # 检查是否含有期望的数据结构
        if 'result' in data_json and 'data' in data_json['result']:
            # 东部联盟数据处理
            eastern_conference = data_json['result']['data']['eastern']
            western_conference = data_json['result']['data']['western']
            comments = []

            # 添加东部联盟数据
            for team in eastern_conference:
                comment = {
                    "conference": "Eastern",
                    "rank": team['rank'],
                    "team_name": team['team_name'],
                    # "tid": team['tid'],
                    "wins": team['wins'],
                    "losses": team['losses'],
                    "win_pct": team['win_pct'],
                    "games_behind": team['games_behind'],
                    "points_for": team['points_for'],
                    "points_against": team['points_against'],
                    "point_diff": team['point_diff'],
                    "home_wins": team['home_wins'],
                    "home_losses": team['home_losses'],
                    "road_wins": team['road_wins'],
                    "road_losses": team['road_losses'],
                    "conference_wins": team['conference_wins'],
                    "conference_losses": team['conference_losses'],
                    "division_wins": team['division_wins'],
                    "division_losses": team['division_losses'],
                    "last_10_wins": team['last_10_wins'],
                    "last_10_losses": team['last_10_losses'],
                    "streak_kind": team['streak_kind'],
                    "streak_length": team['streak_length']
                }
                comments.append(comment)

            # 添加西部联盟数据
            for team in western_conference:
                comment = {
                    "conference": "Western",
                    "rank": team['rank'],
                    "team_name": team['team_name'],
                    # "tid": team['tid'],
                    "wins": team['wins'],
                    "losses": team['losses'],
                    "win_pct": team['win_pct'],
                    "games_behind": team['games_behind'],
                    "points_for": team['points_for'],
                    "points_against": team['points_against'],
                    "point_diff": team['point_diff'],
                    "home_wins": team['home_wins'],
                    "home_losses": team['home_losses'],
                    "road_wins": team['road_wins'],
                    "road_losses": team['road_losses'],
                    "conference_wins": team['conference_wins'],
                    "conference_losses": team['conference_losses'],
                    "division_wins": team['division_wins'],
                    "division_losses": team['division_losses'],
                    "last_10_wins": team['last_10_wins'],
                    "last_10_losses": team['last_10_losses'],
                    "streak_kind": team['streak_kind'],
                    "streak_length": team['streak_length']
                }
                comments.append(comment)

            # 将数据写入csv文件，使用原始字符串避免转义字符问题
            save_path = r'data.csv'
            with open(save_path, 'a', newline='', encoding='utf-8') as fp:
                # 修改列名为图片中显示的列名
                csv_header = ["联盟", "排名", "球队", "胜", "负", "胜率", "胜差", "得分", "失分", "分差", "主场战绩",
                              "客场战绩", "分部战绩", "分区战绩", "最近十场", "连胜连负"]

                # 打开文件准备写入，如果文件不存在，将会被创建
                with open(save_path, 'w', newline='', encoding='utf-8') as fp:  # 使用 'w' 模式来覆盖文件
                    csv_writer = csv.DictWriter(fp, fieldnames=csv_header)

                    # 写入列头
                    csv_writer.writeheader()

                    # 写入数据
                    for comment in comments:
                        # 使用 f-string 格式化字符串，并且使用条件表达式来决定 “连胜连负” 的值
                        row_data = {
                            "联盟": comment.get("conference"),
                            "排名": comment.get("rank"),
                            "球队": comment.get("team_name"),
                            "胜": comment.get("wins"),
                            "负": comment.get("losses"),
                            "胜率": comment.get("win_pct"),
                            "胜差": int(comment.get('wins', 0)) - int(comment.get('losses', 0)),
                            "得分": comment.get("points_for"),
                            "失分": comment.get("points_against"),
                            "分差": int(comment.get("points_for", 0)) - int(comment.get("points_against", 0)),
                            "主场战绩": f"{comment.get('home_wins')}胜{comment.get('home_losses')}负",
                            "客场战绩": f"{comment.get('road_wins')}胜{comment.get('road_losses')}负",
                            "分部战绩": f"{comment.get('conference_wins')}胜{comment.get('conference_losses')}负",
                            "分区战绩": f"{comment.get('division_wins')}胜{comment.get('division_losses')}负",
                            "最近十场": f"{comment.get('last_10_wins')}胜{comment.get('last_10_losses')}负",
                            "连胜连负": f"{comment.get('streak_length')}胜" if comment.get(
                                "streak_kind") == "win" else f"{comment.get('streak_length')}负"
                        }
                        # 写入一行数据
                        csv_writer.writerow(row_data)
    except json.JSONDecodeError as e:
        print(f"解析JSON时出错: {e}")
else:
    print(f"请求失败，状态码：{response.status_code}")
